package middleware

import (
	"net/http"
	"ruanGongKeShe16Zu/common/utils"
	"ruanGongKeShe16Zu/db"
	"ruanGongKeShe16Zu/model"
	"ruanGongKeShe16Zu/response"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//获取authorization header
		tokenString := ctx.GetHeader("Authorization")

		//validate token format
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			response.Response(ctx, http.StatusUnauthorized, 401, nil, "权限不足")

			//抛弃该Context
			ctx.Abort()
			return
		}
		tokenString = tokenString[7:]
		_, claims, _ := utils.ParseToken(tokenString)
		// if err != nil || !token.Valid {
		// 	response.Response(ctx, http.StatusUnauthorized, 401, nil, "权限不足")
		// 	ctx.Abort()
		// 	return
		// }
		//验证通过后获取claim中的UserId
		userId := claims.UserId
		DB := db.GetDB()
		var user model.User
		DB.First(&user, userId)

		if user.ID == 0 {
			response.Response(ctx, http.StatusUnauthorized, 401, nil, "权限不足")
			ctx.Abort()
			return
		}

		//用户存在 将user信息写入上下文
		ctx.Set("user", user)

		ctx.Next()
	}
}
